//
//  UserAccount.swift
//  weibo
//
//  Created by sanya on 15/6/25.
//  Copyright © 2015年 sanya. All rights reserved.
//

import UIKit
import AFNetworking
class UserAccount: NSObject,NSCoding{
    /// 用于调用access_token，接口获取授权后的access token
    var access_token: String
    /// access_token的生命周期，单位是秒数(实际是数值！)
    var expires_in: NSTimeInterval
    /// 当前授权用户的UID
    var uid: String
    /// 过期时间
    var expiresDate:NSDate
    
    /// 友好显示名称
    var name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    /// 字典转模型
    init(dict: [String: AnyObject]){
        access_token = dict["access_token"] as! String
        expires_in = dict["expires_in"] as! NSTimeInterval
        uid = dict["uid"] as! String
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        
    }
    /// 加载用户信息
    func loadUserInfo(finished:(accout:UserAccount?,error:NSError?) ->()){
        
        let params = ["access_token":access_token,"uid":uid]
        NetworkTools.shareNetworkTools().GET("2/users/show.json", parameters: params, success: { (_, json) -> Void in
            
            let dict = json as! [String:AnyObject]
            self.name = dict["name"] as? String
            self.avatar_large = dict["avatar_large"] as? String
            // 目前保存信息，账号信息才是完整的
            self.saveAccount()
            finished(accout: self, error: nil)
            
            }) { (_, error) -> Void in
                finished(accout: nil, error: error)

        }

    }
 
    /// 打印对象信息
    override var description:String{
    
        let properties = ["access_token", "expires_in", "uid","expiresDate","name","avatar_large"]

        return "\(self.dictionaryWithValuesForKeys(properties))"
    }
    // MARK: -保存和加载文件
    /// 归档路径,Swift中的类常量都是使用static定义的
    static let accountDoc = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask , true).last!.stringByAppendingPathComponent("account.plist")
    
    /// 将当前对象归档保存至沙盒“keyed” 键值归档/解档
    func saveAccount(){
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountDoc)
    
    }
    
    /// 解档 注意：如果之前没有归档，可能会返回 nil
    class func loadAccount() -> UserAccount? {
        // 判断是否过期
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountDoc) as? UserAccount{
            // 判断日期是否过期，根当前系统时间进行`比较`，低于当前系统时间，就认为过期
            // 过期日期`大于`当前日期，结果应该是降序
            if account.expiresDate.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
        return nil
    }
    
    // MARK: - NSCoding 归档接档使用的 key 保持一致即可
    /// 解档方法：aDecoder解码器 将保存在磁盘的二进制文件转换成 对象，和反序列化很像
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as! String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as! NSDate
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String

    }
    /// 归档，aCoder 编码器，将对象转换成二进制数据存储到磁盘上，和序列化很像
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    }

}
